<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions() {
      this.chart.setOption({
        legend: {
          top: "5%",
          left: "0%",
          // doesn't perfectly work with our tricks, disable it
          selectedMode: false,
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        series: [
          {
            itemStyle: {
              normal: {
                color: function (colors) {
                  var colorList = ["#59a4ff", "#ffbd2a", "#b926de"];
                  return colorList[colors.dataIndex];
                },
              },
            },
            type: "pie",
            radius: "80%",
            label: {
              show: true,
              formatter(param) {
                console.log({ param });
                // correct the percentage
                return param.name + " (" + param.percent + "%)";
              },
            },
            data: [
              { value: 600, name: "公海客户" },
              { value: 300, name: "潜在客户" },
              { value: 100, name: "正式客户" },
            ],
          },
        ],
      });
    },
  },
};
</script>
